import PureUnitOperator from '../components/unit-operator';
import * as BuilderAction from 'actions/builder';
import { invalidateCache } from 'actions/util';
import * as RunnableGroupAction from 'actions/runnable-group';
import * as ReactRedux from 'react-redux';

const mapDispatchToProps = (dispatch, ownProps) => {
  const { id: unitId, runtimeId } = ownProps.unit;

  return {
    onNewBuild: () => {
      return dispatch(BuilderAction.newBuild(unitId))
        .then(({ error }) => {
          if (!error) {
            invalidateCache(RunnableGroupAction.listUnitsByRuntimeId, runtimeId);
            dispatch(RunnableGroupAction.listUnitsByRuntimeId(runtimeId));
          }
        });
    },
    onCancelBuild: (uuid) => {
      return dispatch(BuilderAction.cancelBuild(uuid))
        .then(({ error }) => {
          if (!error) {
            invalidateCache(RunnableGroupAction.listUnitsByRuntimeId, runtimeId);
            dispatch(RunnableGroupAction.listUnitsByRuntimeId(runtimeId));
          }
        });
    }
  };
};

export default ReactRedux.connect(undefined, mapDispatchToProps)(PureUnitOperator);
